import qs from 'qs';

export const fetchData = async (
  params:Record<string, any>,
  onProgress: (result: string) => void,
  onEnd: () => void,
) => {
  const response = await fetch('http://localhost:8080/ai/agent', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: qs.stringify(params),
    credentials: 'include',
  });
  if (!response.ok) {
    console.error('Request failed with status:', response.status);
    return;
  }

  // @ts-ignore
  const reader = response.body.getReader();
  const decoder = new TextDecoder('utf-8', { fatal: true });
  let done = false;

  function read() {
    reader
      .read()
      .then(({ value, done: doneReading }) => {
        done = doneReading;
        let s = decoder.decode(value, { stream: true });
        const parts = s.split('data:');
        parts.forEach((part) => {
          if (part.startsWith('data')) {
            part = s.substring(5);
          }
          part = part.replaceAll('\n\n', '');
          onProgress(part);
        });

        if (done) {
          onEnd();
        } else {
          read();
        }
      })
      .catch((error) => {
        console.error('Error while reading stream:', error);
      });
  }

  read();
  console.log('Stream complete.');
};
